﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Data.OleDb;
namespace WebSite_CodeMan.BaseClass
{
    public class BaseClass
    {
        /// <summary>
        /// 将指定路径中的文件内容读出来 以字符串形式返回
        /// </summary>
        /// <param name="filenam">文件相对路径</param>
        /// <returns></returns>
        public static string ReadFiles(string filePath)
        {
            if (File.Exists(filePath))
            {
                //读取文本　
                StreamReader sr = new StreamReader(filePath, System.Text.Encoding.Default);
                string str = sr.ReadToEnd();
                sr.Close();
                return str;
            }
            else
                return "";
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="fileUp">上传控件</param>
        /// <param name="fileExtension">上传文件类型</param>
        public static int UpFile(System.Web.UI.Page page, System.Web.UI.WebControls.FileUpload fileUp, string fileExtension, string strNewName)
        {
            //上传结果 0未知 1成功  -1文件格式有误 -2文件太大
            int strValue = 0;
            string fileName = fileUp.FileName;
            FileInfo fileinfo = new FileInfo(fileName);
            switch (fileExtension)
            {
                case "img":
                    if (fileinfo.Extension.ToLower() == ".gif" || fileinfo.Extension.ToLower() == ".jpg" || fileinfo.Extension.ToLower() == ".png" || fileinfo.Extension.ToLower() == ".bmp")
                    {
                        if (fileUp.PostedFile.ContentLength <= Convert.ToInt64(Common.GetMes.GetConfigAppValue("ImageSize")))
                        {
                            UpLoadFile(page, fileUp, Common.GetMes.GetConfigAppValue("FCKeditor:UserFilesPath") + "/Images/", strNewName);
                            strValue = 1;
                        }
                        else
                        {
                            return -2; //文件太大 !
                        }
                    }
                    else
                    {
                        return -1; //格式有误！
                    }
                    break;
                case "File":
                    if (fileinfo.Extension.ToLower() == ".swf")
                    {
                        UpLoadFile(page, fileUp, Common.GetMes.GetConfigAppValue("FCKeditor:UserFilesPath") + "/Files/", strNewName);
                        strValue = 1;
                    }
                    else
                    {
                        return -1; //格式有误！
                    }
                    break;
                default:
                    break;
            }
            return strValue;
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="page">页面对象</param>
        /// <param name="fileload">上传控件</param>
        /// <param name="strPath">路径</param>
        private static void UpLoadFile(System.Web.UI.Page page, System.Web.UI.WebControls.FileUpload fileload, string strPath, string strNewName)
        {
            string ServerPath = page.Server.MapPath(strPath);
            if (!Directory.Exists(ServerPath))
            {
                //若文件目录不存在 则创建
                Directory.CreateDirectory(ServerPath);
            }
            ServerPath += strNewName;
            try
            {
                fileload.SaveAs(ServerPath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 检测用户状态
        /// </summary>
        public static void CheckState()
        {

            if (string.IsNullOrEmpty(Common.GetMes.GetSessionByCookie("UserID")))
            {
                Common.CheckMes.CheckState("UserID", "../Sys_CodeMan_Manage/Admin_UserLogin.aspx", "请登录后再进行操作......");
            }
        }
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>　　
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode, string imageType)
        {
            Image originalImage = Image.FromFile(originalImagePath);
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）　　　　　　　　
                    break;
                case "W"://指定宽，高按比例　　　　　　　　　　
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）　　　　　　　　
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            //新建一个bmp图片
            Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
              new Rectangle(x, y, ow, oh),
              GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                switch (imageType.ToLower())
                {
                    case "gif":
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif);
                        break;
                    case "jpg":
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        break;
                    case "bmp":
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp);
                        break;
                    case "png":
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
                        break;
                    default:
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        break;
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        /// <summary>
        /// 自定义加密密码
        /// </summary>
        /// <param name="strPass"></param>
        /// <returns></returns>
        public static string PassEnCode(string strPass)
        {
            return Common.EncryptString.MyEncrypt(Common.EncryptString.EncryptMD5(strPass).Substring(0, 15), false);
        }
        ///   <summary>
        ///   过滤HTML，JAVASCRIPT 标记
        ///   </summary>
        ///   <param   name="Htmlstring">包括HTML的源码   </param>
        ///   <returns>已经去除后的文字</returns>
        public static string NoHTML(string Htmlstring)
        {
            //删除脚本
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "",
              RegexOptions.IgnoreCase);
            //删除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "   ",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "",
              RegexOptions.IgnoreCase);
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            return Htmlstring;
        }
        /// <summary>
        /// 载入类别信息
        /// </summary>
        public static void GetNoteClassMes(System.Web.UI.WebControls.DropDownList DDLProClass)
        {
            OleDbDataReader DataRead = BLL.NoteInfo.GetNoteClassMes("");
            if (DataRead.HasRows)
            {
                while (DataRead.Read())
                {
                    System.Web.UI.WebControls.ListItem newItem = new System.Web.UI.WebControls.ListItem(CheckClassNameLeave(DataRead["T_ClassName"].ToString() + "[" + DataRead["T_ClassEnName"].ToString() + "]", DataRead["T_ClassLeave"].ToString()),DataRead["T_NoteClassID"].ToString());
                    DDLProClass.Items.Add(newItem);
                }
            }
            DataRead.Close();
            DataRead.Dispose();
            if (DDLProClass.Items.Count > 0)
            {
                DDLProClass.SelectedIndex = 0;
            }
        }
        /// <summary>
        /// 生成层次结构
        /// </summary>
        /// <param name="strClassName"></param>
        /// <param name="strLeave"></param>
        /// <returns></returns>
        public static string CheckClassNameLeave(string strClassName, string strLeave)
        {
            string[] strName = strLeave.Split(',');
            string[] strTop = { "", "-┗━", "--┗━", "---┗━", "----┗━", "-----┗━" };
            strClassName = (strName.Length == 1) ? strClassName : (strTop[strName.Length - 1] + strClassName);
            return strClassName;
        }
        /// <summary>
        /// 替换表情图片
        /// </summary>
        /// <param name="Note"></param>
        /// <returns></returns>
        public static string ReplaceFace(string Note)
        {
            if (Note.CompareTo("表情") > 0)
            {
                Note = Note.Replace("表情一","<img src=\"../Images/Face/1.gif\" />");
                Note = Note.Replace("表情2","<img src=\"../Images/Face/2.gif\" />");
                Note = Note.Replace("表情3","<img src=\"../Images/Face/3.gif\" />");
                Note = Note.Replace("表情4","<img src=\"../Images/Face/4.gif\" />");
                Note = Note.Replace("表情5","<img src=\"../Images/Face/5.gif\" />");
                Note = Note.Replace("表情6","<img src=\"../Images/Face/6.gif\" />");
                Note = Note.Replace("表情7","<img src=\"../Images/Face/7.gif\" />");
                Note = Note.Replace("表情8","<img src=\"../Images/Face/8.gif\" />");
                Note = Note.Replace("表情9","<img src=\"../Images/Face/9.gif\" />");
                Note = Note.Replace("表情10","<img src=\"../Images/Face/10.gif\" />");
                Note = Note.Replace("表情11","<img src=\"../Images/Face/11.gif\" />");
                Note = Note.Replace("表情12","<img src=\"../Images/Face/12.gif\" />");
                Note = Note.Replace("表情13","<img src=\"../Images/Face/13.gif\" />");
                Note = Note.Replace("表情14","<img src=\"../Images/Face/14.gif\" />");
                Note = Note.Replace("表情15","<img src=\"../Images/Face/15.gif\" />");
            }
            return Note;
        }
        /// <summary>
        /// 根据IP地址 返回所在地区名称
        /// </summary>
        /// <param name="strIP"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public static string GetNameByIP(string strIP,System.Web.UI.Page page)
        {
            string strName = "未知区域";
            if (!string.IsNullOrEmpty(strIP))
            {
                try
                {
                    string ConIPData = page.Server.MapPath("~/App_Data/qqwry.dat");
                    strName = IPLocation.IPLocation.IPLocate(ConIPData, strIP.Trim());
                    if (string.IsNullOrEmpty(strName)) strName = "未知区域";
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return strName.Trim();
        }
        
    }
}
